// 根据 key 找到相应的id值
function getUrlParams (key) {
    var str = location.search.substr(1);
    var arr = str.split('&');
    for(var i=0; i < arr.length; i++) {
        var arr1 = arr[i].split('=');
        if(arr1[0] == key) {
            return arr1[1];
        }
    }
}

var id = getUrlParams('id');
console.log(id);

$.ajax({
      type:'get',
      url:`/posts/${id}`,
      success:function(res){
        $.ajax({
          type:'get',
          url:'/categories',
          success:function(res1){             
            console.log(res)
            res.cateList = res1;//把分类的数据作为res的属性
          
           
            //渲染数据应该确保两个ajax的数据都回来才能去做
            var html = template('modifyTpl',res);
            $('#modifyBox').append(html);
          }
        })
      }
    })

$('#modifyBox').on('change', '#feature', function(){
    var fd = new FormData();
    fd.append('avatar', this.files[0]);
    console.log(fd);
    $.ajax({
        type:'post',
        url: '/upload',
        processData: false,
        contentType: false,
        data: fd,
        success (res) {
            console.log(res);
            $('#preview').attr('src', res[0].avatar).show();
            $('#hiddenImg').val(res[0].avatar);
        }
    }) 
})

//提交修改过的表单
$('#modifyBox').on('submit', '#addForm', function () {
    
    
    $.ajax({
        type:'put',
        url:`/posts/${id}`,
        data: $(this).serialize(),
        success(res){
            console.log(res);
            location.href = 'posts.html'
        }
    })

    return false;
})